package services

import (
	"base_server/internal/models/fashion"
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	common "jihe.common"
	"jihe.common/oss"
	"jihe.common/protos/base_server"
	"jihe.common/protos/base_server/proto"
	"jihe.common/protos/calculate_server"
	calculate_server_proto "jihe.common/protos/calculate_server/proto"
	"jihe.common/tool"
	"strings"
	"time"
)

func UpdateDxfInfo(fashionId, dxfUrl, objUrl, cutpartBorderPointUrl string, cutpartList []*proto.BaseCutpart) (newUrl string, err error) {
	pgsql := new(common.Pgsql)
	fashionTbl := fashion.NewModel(pgsql.Get())
	vtInfos := make([]base_server.VtInfo, 0)
	_, orgjsonByte, errs := tool.GetRequest().Get(strings.Replace(cutpartBorderPointUrl, "files.dizanz", "jihe-file.oss-cn-beijing-internal.aliyuncs", -1)).EndBytes()
	if len(errs) != 0 {
		err = errs[0]
		return
	}
	err = json.Unmarshal(orgjsonByte, &vtInfos)
	if err != nil {
		return
	}
	algorithmParam := &proto.BaseFashionAlgorithmParam{}
	for dx, v := range cutpartList {
		getDxfInfoReq := base_server.DxfInfoReq{}
		getDxfInfoReq.CpName = v.Code
		getDxfInfoReq.DxfPath = strings.Replace(dxfUrl, "files.dizanz", "jihe-file.oss-cn-beijing-internal.aliyuncs", -1)
		getDxfInfoReq.ResourcePath = strings.Replace(v.ObjUrl, "files.dizanz", "jihe-file.oss-cn-beijing-internal.aliyuncs", -1)
		getDxfInfoReqByte, _ := json.Marshal(getDxfInfoReq)
		dxfInfoRet, e := calculate_server.GetDxfInfo(context.Background(), &calculate_server_proto.GetDxfInfoReq{
			Base64: base64.StdEncoding.EncodeToString(getDxfInfoReqByte),
		})
		if e != nil {
			err = e
			return
		}
		dxfInfo := base_server.DxfInfo{}
		err = json.Unmarshal([]byte(dxfInfoRet.Stdout), &dxfInfo)
		if err != nil {
			err = fmt.Errorf("%s", dxfInfoRet.Stdout)
			return
		}
		if dx == 0 {
			algorithmParam = &proto.BaseFashionAlgorithmParam{UvWidth: fmt.Sprintf("%v", dxfInfo.UvcloLength)}
		}
		for dx, item := range vtInfos {
			if item.Code == v.Code {
				vtInfos[dx].DxfInfo = dxfInfo
			}
		}
	}
	bucket, err := oss.GetClient().Bucket("jihe-file")
	if err != nil {
		return
	}
	jsonByte, err := json.Marshal(vtInfos)
	if err != nil {
		return
	}
	fileName := fmt.Sprintf("%s/%d.json", time.Now().Format("2006-01-02"), tool.GetSnowflakeId())
	err = bucket.PutObject(fileName, bytes.NewReader(jsonByte))
	if err != nil {
		return
	}
	err = fashionTbl.UpdateAlgorithmParamById(fashionId, algorithmParam)
	if err != nil {
		return
	}
	newUrl = "https://files.dizanz.com/" + fileName
	return
}
